package com.gzbugu.polytechsasia.dao;

import java.util.*;
import java.sql.*;
import java.io.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据库底层驱动注册、连接、施放资源
 * 
 * @author gauze
 * 
 */
public class DatabaseLinkDAO {

	private static Logger log = LoggerFactory.getLogger(DatabaseLinkDAO.class);

	/* 注册驱动 */
	static {
		try {
			log.info("注册驱动...");
			Class.forName("com.mysql.jdbc.Driver");
			log.info("注册驱动成功");
		} catch (ClassNotFoundException e) {
			log.error("注册驱动失败", e);
		}
	}

	/* 连接数据库 */
	public static Connection getConnection() {
		String url;
		String userName;
		String password;
		Connection conn = null;
		try {
			log.debug("connecting ...");
			Properties props = new Properties();
			InputStream in = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("database.properties");
			props.load(in);
			in.close();

			url = props.getProperty("jdbc.url");
			userName = props.getProperty("jdbc.username");
			password = props.getProperty("jdbc.password");
			conn = DriverManager.getConnection(url, userName, password);
			log.debug("connect successful");
		} catch (FileNotFoundException e) {
			log.error("connect failed", e);
		} catch (IOException e) {
			log.error("connect failed", e);
		} catch (SQLException e) {
			log.error("connect failed", e);
		}
		return conn;
	}

	/* 释放资源 */
	public static void free(ResultSet rs, Statement stat, Connection conn) {
		try {
			log.debug("free resultSet");
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			log.error("free resultSet failed", e);
		} finally {
			try {
				log.debug("free statement");
				if (stat != null)
					stat.close();
			} catch (SQLException e) {
				log.error("free statement failed", e);
			} finally {
				try {
					log.debug("free connection");
					if (conn != null)
						conn.close();
				} catch (SQLException e) {
					log.error("free connection failed", e);
				}
			}
		}
	}

}
